<script setup lang="ts">
import Content from '@/components/Content/index.vue'
import UploadPictureProgress from '@/components/UploadPictureProgress/index.vue'
import TranscodingPicture from '@/components/TranscodingPicture/index.vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { useAuth } from '@/stores/index'
import type { Emits } from './utils/types'
import type { FormRules, FormInstance } from 'element-plus'
import APIUploadMaterial from '@/api/upload-material'
import { EditPen } from '@element-plus/icons-vue'
import { formatBytes } from '@/utils/index'

const $router = useRouter()
const $emit = defineEmits<Emits>()

const filesObject = ref<File[]>([])
const isPushPicList = ref<any[]>([])

const { info } = storeToRefs(useAuth())

const fileRef = shallowRef<HTMLInputElement>()
const disabledUploadFiles = shallowRef<boolean>(false)

function handleSelectFile() {
    if (((isPushPicList.value.length + filesObject.value.length) >= 10) && !info.value.shop_id) {
        ElMessageBox.confirm(
            '未中请店铺权限，限制上传10个产品数量，是否去申请开通店铺？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            $emit('close')
            $router.push({
                name: 'Store'
            })
        }).catch(() => { })
        return
    }
    fileRef.value?.click()
}

function onChangeFile(e: Event) {
    const dom = e.target as HTMLInputElement
    const files = dom.files
    if (!files) return
    console.log(files)
    for (let file of files) {
        if (!file.type.includes('image')) {
            dom.value = ''
            ElMessage.error('只能上传图片文件类型')
            return
        } else {
            filesObject.value.push(file)
        }
    }
    dom.value = ''
}
const uploadProgressRefs = ref<InstanceType<typeof UploadPictureProgress>[]>([])

function handleUploadFiles() {
    disabledUploadFiles.value = true
    uploadProgressRefs.value[0].handleUpload()
}

function onRemove(index: number) {
    filesObject.value.splice(index, 1)
}

const transcodingPicture = ref<any[]>([])

function onSuccess(code: string, index: number) {
    const nextIndex = index + 1
    transcodingPicture.value.push(code)
    if (nextIndex < uploadProgressRefs.value.length) {
        const nextElement = uploadProgressRefs.value[nextIndex]
        nextElement.handleUpload()
    } else {
        ElMessage.success('已全部上传完毕')
        filesObject.value = []
        disabledUploadFiles.value = false
    }
}

const loading = shallowRef<boolean>(false)

function getIsPushPic() {
    loading.value = true
    APIUploadMaterial.getIsPushPic().then(({ data }) => {
        isPushPicList.value = data
    }).finally(() => {
        loading.value = false
    })
} getIsPushPic()


const dialogVisible = shallowRef<boolean>(false)

function handleShowDialogVisible(item: any) {
    if (!info.value.shop_id) {
        ElMessageBox.confirm(
            '暂未入驻店铺，是否前往入驻店铺？',
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            $emit('close')
            $router.push({
                name: 'Store'
            })
        }).catch(() => { })
        return
    }
    const { goods_id } = item
    picGetEditSDetail(goods_id)
    dialogVisible.value = true
}

const editSDetail = ref<any>({})

function picGetEditSDetail(goods_id: number) {
    APIUploadMaterial.picGetEditSDetail(goods_id).then(({ data }) => {
        editSDetail.value = data
        formData.value.goods_id = goods_id
        formData.value.authors = JSON.parse(JSON.stringify(editSDetail.value.AuthorList))
        formData.value.title = data.title

        if (editSDetail.value.status == 2) {
            formData.value.title = editSDetail.value.title
            formData.value.brief = editSDetail.value.brief
            formData.value.key = editSDetail.value.key
            formData.value.profit = editSDetail.value.profit
        }
    })
}

function handleClose() {
    dialogVisible.value = false
}
const formData = ref<any>({
    profit: 50
})

function handlePriceClear() {
    formData.value.authors.forEach((item: any) => {
        item.market_price = 0
        item.get_price = 0
    })
}

function handlePriceAuto() {
    formData.value.authors.forEach((item: any, index: number) => {
        if (!editSDetail.value.AuthorList) return
        item.market_price = editSDetail.value?.AuthorList[index]?.market_price
        item.get_price = editSDetail.value?.AuthorList[index]?.get_price
    })
}

const dialogInnerVisible = shallowRef<boolean>(false)

const rules = reactive<FormRules<any>>({
    title: [{
        required: true, message: '请输入标题', trigger: 'blur',
    }, {
        max: 40, message: '标题不可以超过40字', trigger: 'blur'
    }],
    brief: [{
        required: true, message: '请输入描述', trigger: 'blur'
    }, {
        max: 200, message: '作品介绍不可以超过40字', trigger: 'blur'
    }],
    key: [{
        required: true, message: '请输入关键字', trigger: 'blur'
    }, {
        pattern: /^([\u4e00-\u9fa5a-zA-Z0-9]+)(\/[\u4e00-\u9fa5a-zA-Z0-9]+){4,}$/,
        message: '不可少于5个关键词，并且不可有特殊符号',
        trigger: 'blur'
    }],
    profit: [{
        required: true, message: '请选择利润', trigger: 'blur'
    }]
})

const ruleFormRef = shallowRef<FormInstance>()

function submitChange() {
    ruleFormRef.value?.validate((valid, fields) => {
        if (valid) {
            const form = { ...formData.value }
            form.authors = JSON.stringify(form.authors)
            form.shop_id = info.value.shop_id
            form.width = editSDetail.value.width
            form.height = editSDetail.value.height
            const loading = ElLoading.service({ lock: true })
            APIUploadMaterial.changePic(form).then(({ msg }) => {
                ElMessage.success('提交成功')
                handleClose()
                getIsPushPic()
            }).finally(() => {
                loading.close()
            })
        } else {
            if (fields?.title && fields?.title?.length != 0) {
                ElMessage.error(fields?.title[0]?.message)
            } else if (fields?.brief && fields?.brief?.length != 0) {
                ElMessage.error(fields?.brief[0]?.message)
            } else if (fields?.key && fields?.key?.length != 0) {
                ElMessage.error(fields?.key[0]?.message)
            } else if (fields?.profit && fields?.profit?.length != 0) {
                ElMessage.error(fields?.profit[0]?.message)
            }
        }
    })
}

/** 监听函数防抖 */
let timer: number | null = null
watch(() => formData.value.title, (newValue) => {
    if (timer !== null) {
        clearTimeout(timer)
    }

    timer = setTimeout(() => {
        if (newValue) {
            APIUploadMaterial.getKey(newValue).then(({ data }) => {
                formData.value.key = data.join('/')
            })
        }
    }, 1000)
})

function onTranscodingSuccess(index: number) {
    transcodingPicture.value.splice(index, 1)
    getIsPushPic()
}

function handleDelete(goods_id?: number) {
    if (!goods_id) return
    ElMessageBox.confirm(
        '是否删除该图片？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        return APIUploadMaterial.deletePic(goods_id)
    }).then(() => {
        ElMessage.success('删除成功')
        getIsPushPic()
    }).catch(() => {
        ElMessage.info('已取消')
    })
}

defineExpose({
    disabledUploadFiles
})
function handleJumpView(type: string, mark: string) {
    window.open(`${import.meta.env.VITE_APP_WEB_URL}/agreement?type=${type}&mark=${mark}`)
}

function handleFree() {
    formData.value.authors.forEach((item: any) => {
        item.get_price = 0
    })
}

</script>

<template>
    <div class="picture">
        <div class="btns">
            <div class="btns-left">
                <button class="btns-left-btn" type="button" @click="handleSelectFile">
                    <p>+</p>
                    <p>上传图片作品（原图）</p>
                </button>
                <input type="file" @change="onChangeFile" style="display: none;" ref="fileRef" accept="image/*"
                    multiple />
            </div>
            <el-button type="danger" class="right" @click="handleUploadFiles" :disabled="disabledUploadFiles"
                v-if="uploadProgressRefs.length != 0">上传</el-button>
        </div>
        <Content class="center">
            <div class="empty" v-if="filesObject.length == 0">在“上传图片作品（原图）”处添加上传文件</div>
            <TransitionGroup name="list">
                <UploadPictureProgress ref="uploadProgressRefs" v-for="(file, index) in filesObject" :key="index"
                    :file="file" @on-remove="onRemove(index)" @on-success="onSuccess($event, index)" />
            </TransitionGroup>
        </Content>
        <div class="push-list" v-loading="loading">
            <TranscodingPicture v-for="(item, index) in transcodingPicture" :key="index" :code="item"
                @on-success="onTranscodingSuccess(index)" />
            <div class="push-item" v-for="item in isPushPicList" :key="item.goods_id">
                <img v-if="item.main_image" :src="item.main_image" alt="图片">
                <div class="push-item-btns" v-if="item.is_push != 2">
                    <span @click="handleShowDialogVisible(item)">编辑</span>
                    <span @click="handleDelete(item.goods_id)">删除</span>
                </div>
                <div class="is-push" v-else>公司审核中...</div>
            </div>
        </div>
        <el-dialog v-model="dialogVisible" title="图片作品编辑" width="1124" :before-close="handleClose" destroy-on-close
            :show-close="false">
            <template #header>
                <DialogClose title="图片作品编辑" @close="handleClose" />
            </template>
            <el-dialog class="zuoping-edit" v-model="dialogInnerVisible" width="1000" :show-close="false">
                <template #header>
                    <DialogClose title="图片价格编辑" @close="dialogInnerVisible = false" />
                    <EditQuestionFilled style="position: absolute; top: 11px; left: 98px;" />
                </template>
                <el-table class="price-edit" :data="formData.authors">
                    <el-table-column label="板块">图片</el-table-column>
                    <el-table-column prop="using_body" label="授权类型" />
                    <el-table-column label="授权详情信息（授权信息可编辑）" min-width="400" v-slot="{ row }">
                        <div v-if="!row.isShowAuthDetilEdit">
                            {{ row.auth_detail }}
                            <el-icon color="#0F40F5" size="20" style="cursor: pointer;position: relative;top: 4px;"
                                @click="row.isShowAuthDetilEdit = true">
                                <EditPen />
                            </el-icon>
                        </div>
                        <el-input v-model="row.auth_detail" v-else :ref="(el: any) => el?.focus()"
                            @blur="row.isShowAuthDetilEdit = undefined" />
                    </el-table-column>
                    <el-table-column label="市场价（元）" min-width="100" v-slot="{ row }">
                        <div v-if="!row.isShowMarketPriceEdit">
                            {{ row.market_price }}
                            <el-icon color="#0F40F5" size="20" style="cursor: pointer;position: relative;top: 4px;"
                                @click="row.isShowMarketPriceEdit = true">
                                <EditPen />
                            </el-icon>
                        </div>
                        <el-input v-model="row.market_price" v-else :ref="(el: any) => el?.focus()"
                            @blur="row.isShowMarketPriceEdit = undefined" />
                    </el-table-column>
                    <el-table-column label="到手价（元）" min-width="100" v-slot="{ row }">
                        <div v-if="!row.isShowGetPriceEdit">
                            {{ row.get_price }}
                            <el-icon color="#0F40F5" size="20" style="cursor: pointer;position: relative;top: 4px;"
                                @click="row.isShowGetPriceEdit = true">
                                <EditPen />
                            </el-icon>
                        </div>
                        <el-input v-model="row.get_price" v-else :ref="(el: any) => el?.focus()"
                            @blur="row.isShowGetPriceEdit = undefined" />
                    </el-table-column>
                </el-table>
                <div class="price-edit-btn">
                    <button type="button" style="background-color: #e6a23c" @click="handleFree">免费售卖</button>
                    <button type="button" @click="handlePriceClear">清除价格</button>
                    <button type="button" @click="handlePriceAuto">使用模板价格</button>
                </div>
                <button class="price-edit-submit" @click="dialogInnerVisible = false">
                    确认
                </button>
            </el-dialog>
            <div class="no-pass" v-if="editSDetail.status == 2">
                不通过原因：{{ editSDetail.reason }}
            </div>
            <div class="picture-edit">
                <div class="left">
                    <img v-if="editSDetail.main_image" :src="editSDetail.main_image" alt="main_image">
                </div>
                <el-form class="form" ref="ruleFormRef" :model="formData" :rules="rules" :show-message="false">
                    <div class="middle">
                        <div class="picture-info">
                            <div>编号：{{ editSDetail.code }}</div>
                            <div>日期：{{ editSDetail.create_time }}</div>
                            <div>大小：{{ formatBytes(Number(editSDetail?.file_size)) }}</div>
                        </div>
                        <div class="item-input">
                            <el-form-item prop="title" style="margin: 0;width: 100%;">
                                <el-input v-model="formData.title" placeholder="标题：请输入不超过40字的标题" style="height: 40px;"
                                    input-style="font-family: 'SOURCEHANSANSCN-EXTRALIGHT'" />
                            </el-form-item>
                        </div>
                        <div class="text">准确描述产品将更易被搜索出来；<span @click="handleJumpView('help', 'title')">标题填写技巧</span>
                        </div>
                        <div class="item-input">
                            <el-form-item prop="brief" style="margin: 0;width: 100%;">
                                <el-input v-model="formData.brief" placeholder="描述：请输入不超过200字的作品介绍" type="textarea"
                                    input-style="font-family: 'SOURCEHANSANSCN-EXTRALIGHT'" />
                            </el-form-item>
                        </div>
                        <div class="text">通过描述吸引更多感兴趣的用户；<span @click="handleJumpView('help', 'breif')">描述填写技巧</span>
                        </div>
                        <div class="item-input">
                            <el-form-item prop="key" style="margin: 0;width: 100%;">
                                <el-input v-model="formData.key" placeholder="不少于5个关键词，关键词与关键词以《 / 》符号隔开；"
                                    style="height: 40px;" input-style="font-family: 'SOURCEHANSANSCN-EXTRALIGHT'" />
                            </el-form-item>
                        </div>
                        <div class="text">可快速使用关键词查找到作品；<span @click="handleJumpView('help', 'keyword')">关键词填写技巧</span>
                        </div>
                    </div>
                    <div class="right">
                        <div class="market-price">
                            <div class="item-input">
                                <button type="button" @click="dialogInnerVisible = true">编辑授权及价格</button>
                            </div>
                            <p>按照授权类型填写销售价格</p>
                        </div>
                        <div class="market-price">
                            <div class="item-input">
                                <el-form-item prop="profit" style="margin: 0;width: 100%;">
                                    <el-select v-model="formData.profit" placeholder="利润">
                                        <el-option v-for="(item, index) in editSDetail.profit_percentage" :key="index"
                                            :label="item.type" :value="item.title">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </div>
                            <p>选择销售出去作品分给平台的利润</p>
                        </div>
                    </div>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false" style="width: 216px; height: 40px;">取消</el-button>
                    <el-button color="rgb(15 64 240)" @click="submitChange" style="width: 216px; height: 40px;">
                        提交
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<style lang="scss">
.price-edit {
    .el-table__header {
        .cell {
            font-family: 'SOURCEHANSANSCN-REGULAR';
        }
    }

    .el-table__body-wrapper {
        .cell {
            font-family: 'SOURCEHANSANSCN-LIGHT';
        }
    }
}
</style>

<style lang="scss" scoped>
.no-pass {
    position: absolute;
    top: 11px;
    left: 135px;
    color: red;
    font-weight: 700;
}

.picture {
    .price-edit-submit {
        width: 230px;
        height: 40px;
        border-radius: 5px;
        background-color: rgba(249, 20, 20, 1);
        color: rgba(255, 255, 255, 1);
        font-size: 14px;
        border: none;
        display: block;
        margin: 0 auto;
        cursor: pointer;
        margin-bottom: 40px;
        margin-top: 20px;
    }

    .price-edit-btn {
        display: flex;
        justify-content: flex-end;
        margin-top: 17px;
        gap: 0 26px;

        button {
            display: block;
            width: 120px;
            height: 40px;
            color: #ffffff;
            background-color: #3F90F7;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }
    }

    .price-edit {
        width: 100%;
        margin-top: 20px;
    }

    .picture-edit {
        display: flex;
        justify-content: center;
        gap: 0 22px;
        margin-top: 30px;

        .right {
            width: 232px;

            .item-input {
                display: flex;

                &::before {
                    content: '*';
                    margin-right: 5px;
                    font-size: 20px;
                    font-weight: 700;
                    color: #F91B1B;
                }
            }

            .market-price {
                button {
                    width: 231px;
                    height: 40px;
                    border-radius: 5px;
                    background-color: rgba(15, 64, 245, 1);
                    color: rgba(255, 255, 255, 1);
                    font-size: 14px;
                    border: none;
                    cursor: pointer;
                }

                p {
                    color: rgba(154, 154, 154, 1);
                    font-size: 14px;
                    margin-bottom: 20px;
                    margin-left: 15px;
                    font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
                }
            }
        }

        .middle {
            width: 500px;

            .item-input {
                display: flex;

                &::before {
                    content: '*';
                    margin-right: 5px;
                    font-size: 20px;
                    font-weight: 700;
                    color: #F91B1B;
                }
            }

            .text {
                margin-left: 20px;
                color: rgba(154, 154, 154, 1);
                font-size: 14px;
                line-height: 1.6em;
                margin-bottom: 20px;
                font-family: 'SOURCEHANSANSCN-EXTRALIGHT';

                span {
                    color: #3F90F7;
                    cursor: pointer;
                }
            }

            .picture-info {
                display: flex;
                gap: 0 10px;
                margin-bottom: 20px;
            }
        }

        .form {
            display: flex;
            gap: 0 22px;
        }

        .left {
            width: 256px;
            height: 256px;
            background-color: #eeeeee;

            img {
                display: block;
                width: 100%;
                height: 100%;
                object-fit: contain;
            }
        }
    }

    .push-list {
        width: 900px;
        display: grid;
        grid-template-columns: repeat(4, 200px);
        margin-top: 54px;
        justify-content: space-between;
        gap: 30px 0;

        .push-item {
            position: relative;

            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }

            .is-push {
                width: 100%;
                height: 100%;
                border-radius: 5px;
                background-color: rgba(0, 0, 0, 0.292);
                position: absolute;
                top: 0;
                left: 0;
                text-align: center;
                line-height: 112px;
                color: #ffffff;
            }

            .push-item-btns {
                box-sizing: border-box;
                position: absolute;
                width: 100%;
                height: 30px;
                background-color: rgba(0, 0, 0, 0.292);
                z-index: 999;
                bottom: 0;
                color: #ffffff;
                font-size: 13px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 0 40px;

                span {
                    cursor: pointer;
                }
            }
        }

        >div {
            box-sizing: border-box;
            height: 112px;
            border-radius: 5px;
            overflow: hidden;
        }
    }


    .center {
        margin-top: 20px;
        min-height: 172px;
        position: relative;
        padding: 8px 12px;
        box-sizing: border-box;

        .empty {
            font-size: 13px;
            color: #9A9A9A;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translateY(-50%) translateX(-50%);
            font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
        }
    }

    .btns {
        display: flex;
        justify-content: space-between;

        .btns-right {
            width: 170px;
            height: 38px;
            line-height: 20px;
            border-radius: 5px;
            font-size: 14px;
            letter-spacing: 5px;
            background-color: #F91B1B;
        }

        .btns-left {
            display: flex;
            gap: 0 34px;

            .btns-left-btn {
                display: flex;
                justify-content: center;
                align-items: center;
                width: 175px;
                height: 38px;
                border: none;
                border-radius: 5px;
                font-size: 14px;
                cursor: pointer;
                background-color: rgba(55, 133, 242, 1);
                color: rgba(255, 255, 255, 1);
                gap: 0 5px;
            }


            .btns-left-btn-music {
                background-color: #ffffff;
                color: #ff0000;
                border: 1px solid rgba(206, 206, 206, 1);
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 0 10px;
            }
        }
    }
}

.list-enter-active,
.list-leave-active {
    transition: all 0.5s ease;
}

.list-enter-from,
.list-leave-to {
    opacity: 0;
    transform: translateX(30px);
}
</style>
